var express = require('express');
var router = express.Router();
var person = require("../src/person");
const multiparty = require('multiparty');
var fs =require("fs");
var configVar = require("../config/code");


router.use(function (req, res, next) {

    if(req.session.userinfo){
        if( req.session.userinfo.type == configVar.type.admin){
            next();
        }else{
          res.status(403).send("禁止访问");
        }
    }else{
        res.send(configVar.login)
    }

})
router.get('/add', function(req, res, next) {
   // person.add(req.params);

    person.add(req.query).then(function (ret) {
        res.send(ret);
    }).catch(function (ret) {
        res.send(ret);
    })
});

router.get('/update', function(req, res, next) {
    // person.add(req.params);

    person.update(req.query).then(function (ret) {
        res.send(ret);
    }).catch(function (ret) {
        res.send(ret);
    })
});

router.post('/child', function(req, res, next) {

    var ids = req.body.ids;
    try {
        ids = JSON.parse(ids);
        person.getById({ids}).then(function (ret) {
            res.send(ret);
        }).catch(function (ret) {
            res.send(ret);
        })
    }catch (e){
        next()
    }

});

//dbPerson.remove

router.post('/remove', function(req, res, next) {

    var child = req.body.child;
    var param = req.body;
    try {

        param.child = JSON.parse(child);
        person.remove( param ).then(function (ret) {
            res.send(ret);
        }).catch(function (ret) {
            res.send(ret);
        })
    }catch (e){
        console.log(e);
        next()
    }

});

router.get('/change/parent', function(req, res, next) {
    // person.add(req.params);

    person.changeParent(req.query).then(function (ret) {
        res.send(ret);
    }).catch(function (ret) {
        res.send(ret);
    })
});



router.post('/file', function(req, res, next) {
    //生成multiparty对象，并配置上传目标路径
    const form = new multiparty.Form()
    // //设置编辑
    form.encoding = 'utf-8'
    // //设置文件存储路径
    form.uploadDir = "./public/static/"
    // //设置单文件大小限制
    //form.maxFilesSize = 2 * 1024 * 1024
    // form.maxFields = 1000;  设置所以文件的大小总和
    // 上传完成后处理


    form.parse(req, (err, fields, files) => {
        if (err) {
            console.log("parse:",err);
            res.json(configVar.fileUp);
        } else {
            const inputFile = files.file[0];
            const uploadedPath = inputFile.path
            var  imgtype = inputFile.originalFilename;
            const typarr = imgtype.split(".");
            const typ = typarr[typarr.length -1];
            const nm =  new  Date().getTime()  +  '' +  Math.floor(Math.random()*1000000) ;
            console.log(fields.old);
            imgtype = nm + '.' + typ;
            const inPath = `./public/static/${imgtype}`; //重命名的路径
            // 判断是否存在./dist/static/files文件
            fs.stat('./public/static', (err, stats) => {
                if (JSON.stringify(stats) === undefined) {
                    fs.mkdirSync('./public/static')
                }
                storeFiles(uploadedPath, fields, inPath)
            });
        }
    });

    function storeFiles(uploadedPath, fields, inPath) {
        //重命名为真实文件名
        fs.rename(uploadedPath, inPath,  (err) => {
            if (err) {
                console.log("rename:",err);
                res.json(configVar.rename);
            } else {
                var ret  = {
                    data:inPath.substring(8)
                };
                Object.assign(ret , configVar.success);
                res.json(ret);
            }
        });
    }

});
module.exports = router;